"""
OpenRouter思考过程提取功能实现
支持从Claude 3.7 Thinking模型响应中提取思考过程
"""
from typing import Dict, Any, List, Optional
import logging

from ...capabilities.base import Capability, register_capability

logger = logging.getLogger("llm.openrouter.thinking")

@register_capability("thinking")
class OpenRouterThinking(Capability):
	"""OpenRouter的思考过程提取实现"""
	
	def _initialize(self) -> None:
		"""初始化功能"""
		self.supported = False
		# 检查模型是否支持思考过程
		model = self.provider.model.lower()
		if "claude" in model and "thinking" in model:
			self.supported = True
		logger.debug(f"初始化OpenRouter思考过程功能，支持状态: {self.supported}")
	
	def is_supported(self) -> bool:
		"""
		检查当前配置是否支持思考过程提取
		
		Returns:
			是否支持思考过程提取
		"""
		return self.supported
	
	def extract_thinking(self, response: Dict[str, Any]) -> Optional[str]:
		"""
		从响应中提取思考过程
		
		Args:
			response: API响应数据
			
		Returns:
			思考过程字符串，如果不存在则返回None
		"""
		if not self.supported:
			return None
			
		try:
			# 处理完整的响应数据
			if isinstance(response, dict):
				# 检查choices
				if "choices" in response and len(response["choices"]) > 0:
					choice = response["choices"][0]
					
					# Claude 3.7思考过程位于model_extra.reasoning
					if "message" in choice and "model_extra" in choice["message"]:
						return choice["message"]["model_extra"].get("reasoning")
					
					# 流式响应中，思考过程位于delta.model_extra.reasoning
					if "delta" in choice and "model_extra" in choice["delta"]:
						return choice["delta"]["model_extra"].get("reasoning")
						
		except Exception as e:
			logger.error(f"提取思考过程时出错: {str(e)}")
			
		return None
